const docx = require("docx");
const fs = require("fs");
const path = require("path");
const { generateSections } = require('./renderers/sections');

const {
    Document,
    Paragraph,
    TextRun,
    AlignmentType,
} = docx;

// 读取 JSON 数据
const data = JSON.parse(fs.readFileSync(path.join(__dirname, 'data.json'), 'utf8'));

// 创建文档
const doc = new Document({
    sections: [{
        properties: {},
        children: [
            // 文档头部
            new Paragraph({
                alignment: AlignmentType.RIGHT,
                spacing: { before: 200, after: 200 },
                children: [
                    new TextRun("方案编号：XXXX"),
                    new TextRun({ text: "    " }),
                    new TextRun("版本号：1.0"),
                    new TextRun({ text: "    " }),
                    new TextRun("版本日期：2025 年 04 月 28 日"),
                ],
            }),

            // 动态生成各个部分
            ...generateSections(data.sections),
        ],
    }],
    styles: {
        default: {
            document: {
                run: {
                    font: "SimSun",
                    size: 21,
                    language: {
                        eastAsia: "zh-CN"
                    }
                }
            },
            heading1: {
                run: {
                    font: "SimSun",
                    size: 28,
                    bold: true
                },
                paragraph: {
                    spacing: { before: 400, after: 200 }
                }
            },
            heading2: {
                run: {
                    font: "SimSun",
                    size: 21,
                    bold: true
                },
                paragraph: {
                    spacing: { before: 200, after: 100 }
                }
            }
        }
    }
});

// 生成文档
const outputDir = path.join(__dirname, "output");
if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir);
}

// 生成单个文档
const outputPath = path.join(outputDir, `form_${Date.now()}.docx`);

docx.Packer.toBuffer(doc).then((buffer) => {
    fs.writeFileSync(outputPath, buffer);
    console.log("文档已生成：" + outputPath);
    
    // 删除其他文档
    fs.readdirSync(outputDir).forEach(file => {
        const filePath = path.join(outputDir, file);
        if (filePath !== outputPath && file.endsWith('.docx')) {
            fs.unlinkSync(filePath);
        }
    });
}); 